<template>
    <div style="border: 1px solid #ccc">
        <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" />
        <Editor style="height: 310px; overflow-y: hidden;" v-model="valueHtml" @onCreated="handleCreated"
            @onChange="onChange" />
    </div>
</template>
<script setup lang="ts">
import { ref, shallowRef, onMounted } from "vue";
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { uploadApi } from '@/api'

//数据流向是单向的， 从父到子
const props = defineProps({ modelValue: { type: String, default: '' } })
const emit = defineEmits(['update:modelValue']) // 触发器，声明。提前给老爹声明一下，我待会可能用动用你的money
//编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
const valueHtml = ref('')
const handleCreated = (editor: any) => {
    editorRef.value = editor // 记录 editor 实例，重要！
    editor.setHtml(props.modelValue)
    editor.getConfig().MENU_CONF['uploadImage'] = {
        // 自定义上传
        async customUpload(file: any, insertFn: any) {  // TS 语法
            // file 即选中的文件
            let reader = new FileReader()
            reader.readAsDataURL(file)
            reader.onload = () => {
                uploadApi.upload.call({ name: file.name, base64: reader.result }).then((res) => {
                    // 自己实现上传，并得到图片 url alt href
                    // 最后插入图片
                    insertFn(res, file.name, "")
                })
            }

        }
    }
    editor.getConfig().MENU_CONF['uploadVideo'] = {
        // 自定义上传
        async customUpload(file: any, insertFn: any) {  // TS 语法
            // file 即选中的文件
            let reader = new FileReader()
            reader.readAsDataURL(file)
            reader.onload = () => {
                uploadApi.upload.call({ name: file.name, base64: reader.result }).then((res) => {
                    // 自己实现上传，并得到图片 url alt href
                    // 最后插入图片
                    insertFn(res,"")
                })
            }

        }
    }


}


onMounted(() => {
    console.log(props.modelValue);
})
const onChange = (editor: any) => {

    emit("update:modelValue", editor.getHtml())

}
</script>